package com.enlorenz.core.engine.imp.timer;

import java.util.Calendar;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

import com.enlorenz.common.util.DataDetUtils;
import com.enlorenz.common.util.TimeUtils;
import com.enlorenz.core.engine.AbstractEngine;
import com.enlorenz.core.engine.IBuzHandler;

/**
 * 每日执行Timer任务
 * @author lcb
 */
public class DailyTimerEngine extends AbstractEngine{
	//内部的计时器Timer
	private Timer timer;
	//业务处理类
	protected IBuzHandler buzHandler;
	//内部时间任务
	private InnerTimeTask innerTimeTask;
	//运行时间，格式HHmmss
	private String time;
	//初始执行时间
	private Date excuteDate;
	/**
	 * 获取初始执行时间
	 * @return
	 */
	public Date getInitExcuteTime(){
		//初始化的执行时间
		Calendar initExecuteTime = Calendar.getInstance();
		int hh=Integer.parseInt(time.substring(0,2));
		int mm=Integer.parseInt(time.substring(2,4));
		int ss=Integer.parseInt(time.substring(4,6));
		initExecuteTime.set(Calendar.HOUR_OF_DAY, hh);
		initExecuteTime.set(Calendar.MINUTE, mm);
		initExecuteTime.set(Calendar.SECOND, ss);
		
		//当前时间
		Date nowDate=new Date();
		if(nowDate.getTime()>initExecuteTime.getTime().getTime())
		{ 
			initExecuteTime.add(Calendar.HOUR_OF_DAY, 24);
		}
		return initExecuteTime.getTime();
	}
	
	/**
	 * 校验时间格式
	 */
	private void validateTime(){
		if(DataDetUtils.isStrEmpty(time)){
			throw new RuntimeException("任务时间为空");
		}
		if(6!=time.length()){
			throw new RuntimeException("任务时间必须为6位");
		}
	}
	
	/**
	 * 初始化Timer
	 */
	@Override
	protected void initEngine() throws Exception {
		//获取初始执行时间
		this.excuteDate=getInitExcuteTime();
		innerTimeTask=new InnerTimeTask();
	}
	
	@Override
	public void shutdownEngine() throws Exception{
		timer.cancel();
	}

	@Override
	public void startEngine() throws Exception{
		timer=new Timer();
		timer.schedule(innerTimeTask, excuteDate, TimeUtils.DAY_MILLI);
	}
	
	@Override
	public boolean isAlive() {
		return true;
	}
	
	/**
	 * 内部Timer任务
	 * @author lcb
	 */
	private class InnerTimeTask extends TimerTask{
		@Override
		public void run() {
			buzHandler.handle();
		}
	}
	/**
	 * 设置运行时间
	 * @param time 运行时间，格式HHmmss
	 */
	public void setTime(String time) {
		this.time = time;
		validateTime();
	}
	/**
	 * 设置业务处理器
	 * @param buzHandler 业务处理器
	 */
	public void setBuzHandler(IBuzHandler buzHandler) {
		this.buzHandler = buzHandler;
	}
	
}
